package com.lgkj.ui.main;

import android.app.ProgressDialog;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.google.gson.Gson;
import com.lgkj.R;
import com.lgkj.adapter.ImpInfoAdapter;
import com.lgkj.bean.NearPropleBean;
import com.lgkj.bean.NearShopBean;
import com.lgkj.utils.CommonConstant;
import com.lgkj.utils.CommonUtils;
import com.lgkj.utils.HttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/6/22 0022.
 */

public class MainNearbyFragment extends SupportMapFragment implements AMap.OnMyLocationChangeListener, LocationSource, AMapLocationListener {
    //view
//    @BindView(R.id.map)
    TextureMapView map;

    private static final String TAG = "MainNearbyFragment";
    //data
    private AMap aMap;
    OnLocationChangedListener mListener;
    AMapLocationClient mlocationClient;
    AMapLocationClientOption mLocationOption;
    ArrayList<MarkerOptions> optionses = new ArrayList<>();
    private double latitude = 0;
    private double longitude = 0;
    private Button btnNearPeople;
    private Button btnNearDian;
    String tag = "MainNearbyFragment";
    private NearPropleBean nearPeopleBean;
    private NearShopBean nearShopBean;
    private ImpInfoAdapter impInfoAdapter;

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        View view = layoutInflater.inflate(R.layout.main_map_fragment, viewGroup, false);
        map = view.findViewById(R.id.map_view);
        btnNearPeople = view.findViewById(R.id.btn_nearperson);
        btnNearDian = view.findViewById(R.id.btn_neardian);
        btnNearPeople.setSelected(true);
        btnNearDian.setSelected(false);
        map.onCreate(bundle);
        btnNearPeople.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(tag, "按钮====" + btnNearPeople.isSelected() + "");
                btnNearPeople.setSelected(true);
                if (btnNearDian.isSelected()) {
                    getLocations();
                }
                btnNearDian.setSelected(false);
            }
        });
        btnNearDian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(tag, "按钮====" + btnNearDian.isSelected() + "");
                btnNearPeople.setSelected(false);
                if (!btnNearDian.isSelected()) {
                    getLocations();
                }
                btnNearDian.setSelected(true);
            }
        });
        if (aMap == null) {
            Log.i(TAG, "onCreateView: ");
            aMap = map.getMap();
            //设置显示定位按钮 并且可以点击
        }else{
            Log.i(TAG, "onCreateView: else");
            aMap.clear();
            aMap.setLocationSource(this);
            aMap.setMyLocationEnabled(true);
            aMap = map.getMap();
        }
        UiSettings settings = aMap.getUiSettings();
        aMap.setLocationSource(this);//设置了定位的监听,这里要实现LocationSource接口
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(true);
        aMap.setMyLocationEnabled(true);//显示定位层并且可以触发定位,默认是flase
        setLocation();
        aMap.setOnMyLocationChangeListener(this);
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
//                double ss=latLng.latitude+latLng.longitude;
                for (int i = 0; i < aMap.getMapScreenMarkers().size(); i++) {
                    if (aMap.getMapScreenMarkers().get(i).isInfoWindowShown())
                        aMap.getMapScreenMarkers().get(i).hideInfoWindow();
                }
            }
        });
        return view;
    }


    /**
     * 定位
     */
    private void setLocation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            ///////实现定位蓝点  5.0以后
            MyLocationStyle myLocationStyle;
            myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
//            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE) ;//定位一次，且将视角移动到地图中心点。
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//只定位一次。
            aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style

//            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
            aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
//            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）默认执行此种模式。
            myLocationStyle.strokeWidth(1.0f);//设置定位蓝点精度圈的边框宽度的方法。
        } else {
            ////////////实现定位蓝点
//            // 设置定位监听
            aMap.setLocationSource(this);
//            // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(true);
//            // 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
            aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //在执行onDestroy时执行mMapView.onDestroy()，销毁地图
        map.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        map.onResume();
        isfirst = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        map.onPause();
    }

    @Override
    public void onMyLocationChange(Location location) {
        //从location对象中获取经纬度信息，地址描述信息，建议拿到位置之后调用逆地理编码接口获取（获取地址描述数据章节有介绍）
        //经读
        latitude = location.getLatitude();
        //纬度
        longitude = location.getLongitude();
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        if (isfirst) {
            isfirst = false;
        }
        getLocations();

    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(getActivity());
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setOnceLocation(true);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位

        }
    }


    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    private boolean isfirst = true;

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                latitude = amapLocation.getLatitude();
                longitude = amapLocation.getLongitude();
                Log.e("定位信息", amapLocation.getLocationDetail().toString());
                if (isfirst) {
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 200));
                    mlocationClient.stopLocation();
                    isfirst = false;
                }
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    ProgressDialog mProgressdialog;

    private void getLocations() {
        if (latitude == 0 || longitude == 0) {
            return;
        }
        final Map<String, String> map = new HashMap<>();
        map.put("lat", latitude + "");
        map.put("lng", longitude + "");
        map.put("access_token", CommonUtils.getToken(getActivity()));
        String url = "";
        if (!btnNearPeople.isSelected()) {
            url = CommonConstant.nearpeople;
        } else {
            url = CommonConstant.nearshop;
        }
        mProgressdialog = ProgressDialog.show(getActivity(), "", "处理中..", true, true);
        HttpUtils.postHttp(map, url, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                mProgressdialog.dismiss();
                if (jsonObject.optInt("code") == 0) {
                    double lat = 0;
                    double lng = 0;
                    if (!btnNearPeople.isSelected()) {
                        nearPeopleBean = new Gson().fromJson(jsonObject.toString(), NearPropleBean.class);
                        Log.i("附近的人", nearPeopleBean.getData().toString());
                        optionses.clear();
                        aMap.clear(true);
                        for (int i = 0; i < nearPeopleBean.getData().size(); i++) {
                            try {
                                lat = Double.parseDouble(nearPeopleBean.getData().get(i).getLat());
                                lng = Double.parseDouble(nearPeopleBean.getData().get(i).getLng());
                                LatLng latLng = new LatLng(lat, lng);
                                MarkerOptions markerOption = new MarkerOptions();
                                markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                        .decodeResource(getResources(),
                                                R.mipmap.near_people)));
                                markerOption.position(latLng);
                                optionses.add(markerOption);
                            } catch (Exception e) {
                                Log.e(TAG, "successHttp: " + e.getMessage());
                            }
                        }
//                        Log.i(TAG, "successHttp: " + optionses.toString());
                        aMap.addMarkers(optionses, false);
                    } else {
                        nearShopBean = new Gson().fromJson(jsonObject.toString(), NearShopBean.class);
                        optionses.clear();
                        aMap.clear(true);
                        for (int i = 0; i < nearShopBean.getData().size(); i++) {
                            try {
                                JSONArray data = jsonObject.getJSONArray("data");
                                lat = Double.parseDouble(nearShopBean.getData().get(i).getBarbershop_lat());
                                lng = Double.parseDouble(nearShopBean.getData().get(i).getBarbershop_lng());
                                LatLng latLng = new LatLng(lat, lng);
                                MarkerOptions markerOption = new MarkerOptions();
                                markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                        .decodeResource(getResources(),
                                                R.mipmap.near_shop)));
                                markerOption.position(latLng).title("2").snippet(data.get(i).toString());
                                optionses.add(markerOption);
                            } catch (JSONException e) {
                                Log.e(TAG, "successHttp: " + e.getMessage());
                            } catch (Exception e) {
                                Log.e(TAG, "successHttp: " + e.getMessage());
                            }
                        }
                        aMap.addMarkers(optionses, false);
                        aMap.setMaxZoomLevel(1000f);
                        impInfoAdapter = new ImpInfoAdapter(getActivity());
                        aMap.setInfoWindowAdapter(impInfoAdapter);
                    }
                } else if (jsonObject.optInt("code") == 1000005) {
                    Toast.makeText(getActivity(), jsonObject.optString("msg"), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void errorHttp(String msg) {
                mProgressdialog.dismiss();
                String str = msg;
                Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
